/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.absisgroup.nt;

import com.absisgroup.nsc.utilities.GenericServlet;
import com.absisgroup.nsc.utilities.Util;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Hue
 */
public class LuuPhieuBanHang extends GenericServlet {

    @Override
    public int process(final Connection con, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
        JSONArray records = new JSONArray(request.getParameter("records"));
        
        String str = save(con, request, records);
        con.commit();
        
        writeToResponse(response, str);

        return DONT_RUN_JSP;
    }

    @Override
    protected boolean useConnection() {
        return true;
    }
    
    private String save(Connection con, HttpServletRequest request, JSONArray records) throws Exception {
        String customer = request.getParameter("customer");
        String address = request.getParameter("address");
        String deposit = request.getParameter("deposit");
        String phone = request.getParameter("phone");
        String seller = request.getParameter("seller");
        Timestamp deliveryDate = Util.toTimestamp(request.getParameter("deliveryDate"), "dd/MM/yyyy HH:mm");
        int orderNum = getOrderNum(con);
        String orderNo = lpad(orderNum);
        Timestamp date = Util.newTimestamp();

        String strQuery = "insert into ORDERS(ORDER_DATE, ORDER_CUSTOMER, ORDER_ADDRESS, ORDER_DEPOSIT, ORDER_PHONE,ORDER_SELLER, ORDER_NUMBER, ORDER_NO, ORDER_DELIVERY) values(?, ?, ?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement pStmt = con.prepareStatement(strQuery);
        int iiIndex = 1;
        pStmt.setTimestamp(iiIndex++, date);
        pStmt.setString(iiIndex++, customer);
        pStmt.setString(iiIndex++, address);
        pStmt.setBigDecimal(iiIndex++, Util.toBigDecimal(deposit));
        pStmt.setString(iiIndex++, phone);
        pStmt.setString(iiIndex++, seller);
        pStmt.setInt(iiIndex++, orderNum);
        pStmt.setString(iiIndex++, orderNo);
        pStmt.setTimestamp(iiIndex++, deliveryDate);
        pStmt.executeUpdate();
        pStmt.close();
        
        pStmt = con.prepareStatement("SELECT LAST_INSERT_ID()");
        ResultSet rs = pStmt.executeQuery();
        BigDecimal orderPK = null;
        if(rs.next()) {
            orderPK = rs.getBigDecimal(1);
        }
        pStmt.close();
        
        StringBuilder sb = new StringBuilder();
        sb.append("insert into ORDERS_DETAILS(ORD_DEATAILS_ORDERS_FK, ORD_DETAILS_STT, ORD_DETAILS_PROD_FK, ORD_DETAILS_DVT, ORD_DETAILS_CHIEU_DAI, ORD_DETAILS_SO_TAM, ORD_DETAILS_SO_LUONG, ORD_DETAILS_DON_GIA, ORD_DETAILS_GHI_CHU)");
        sb.append("values(?, ?, ?, ?, ?, ?, ?, ?, ?)");
        pStmt = con.prepareStatement(sb.toString());
        int iLength = records.length();
        for(int i=0; i<iLength; i++) {
            JSONObject jsObj = records.getJSONObject(i);
            int iIndex = 1;
            pStmt.setBigDecimal(iIndex++, orderPK);
            pStmt.setInt(iIndex++, jsObj.getInt("stt"));
            pStmt.setString(iIndex++, jsObj.getString("prodPK"));
            pStmt.setString(iIndex++, jsObj.getString("dvt"));
            pStmt.setBigDecimal(iIndex++, Util.toBigDecimal(jsObj.getString("chieuDai")));
            pStmt.setBigDecimal(iIndex++, Util.toBigDecimal(jsObj.getString("soTam")));
            pStmt.setBigDecimal(iIndex++, Util.toBigDecimal(jsObj.getString("soLuong")));
            pStmt.setBigDecimal(iIndex++, Util.toBigDecimal(jsObj.getString("donGia")));
            pStmt.setString(iIndex++, jsObj.getString("ghiChu"));
            pStmt.addBatch();
        }
        pStmt.executeBatch();
        pStmt.close();
        
        final JSONObject jsObj = new JSONObject();
        jsObj.put("success", true);
        jsObj.put("records", records);
        if(orderPK != null) {
            jsObj.put("orderPK", orderPK.longValue());
        }
        jsObj.put("customer", customer);
        jsObj.put("address", address);
        jsObj.put("deposit", deposit);
        jsObj.put("phone", phone);
        jsObj.put("seller", seller);
        jsObj.put("orderNo", orderNo);
        //dateText [
        Properties texts = Util.getAppTexts(getServletContext());
        String dateText = texts.getProperty("NGAY_THANG_NAM");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        dateText = Util.replace(dateText, "{0}", String.valueOf(cal.get(Calendar.DATE)));
        dateText = Util.replace(dateText, "{1}", String.valueOf(cal.get(Calendar.MONTH) + 1));
        dateText = Util.replace(dateText, "{2}", String.valueOf(cal.get(Calendar.YEAR)));

        jsObj.put("dateText", dateText);
        //]
        jsObj.put("deliveryDate", getDeliveryDateText(texts, deliveryDate));

        return jsObj.toString();
    }
    
    private String getDeliveryDateText(Properties texts, Date date) {
        if(date == null) {
            return "";
        }
        String dateText = texts.getProperty("NGAY_THANG_NAM_GIO_PHUT");
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        dateText = Util.replace(dateText, "{0}", String.valueOf(cal.get(Calendar.HOUR_OF_DAY)));
        dateText = Util.replace(dateText, "{1}", String.valueOf(cal.get(Calendar.MINUTE)));
        dateText = Util.replace(dateText, "{2}", String.valueOf(cal.get(Calendar.DATE)));
        dateText = Util.replace(dateText, "{3}", String.valueOf(cal.get(Calendar.MONTH) + 1));
        dateText = Util.replace(dateText, "{4}", String.valueOf(cal.get(Calendar.YEAR)));
        return dateText;
    }
    
    private int getOrderNum(Connection con) throws SQLException {
        String strQuery = "select max(ORDER_NUMBER) + 1 from ORDERS";
        PreparedStatement pStmt = con.prepareStatement(strQuery);
        ResultSet rs = pStmt.executeQuery();
        int orderNum = 1;
        if(rs.next()) {
            orderNum = rs.getInt(1);
        }
        pStmt.close();
        
        return (orderNum <= 0 ? 1 : orderNum);
    }

    private String lpad(int value) {
        int maxLength = 9;
        String str = String.valueOf(value);
        while(str.length() < maxLength) {
            str = "0" + str;
        }
        return 'A' + str;
    }
}
